<!-- 失物招领 -->
<template>
  <div class="ShoppingInfo" v-if="ShoppingInfo">
    <myheader title="物品详情" rightBtn="购买记录" @updataInfo="submitRecruit"></myheader>

    <van-swipe lazy-render>
      <van-swipe-item
        style="height:200px;"
        v-for="(items,indexs)  in  imgList "
        :key="indexs"
        @click.stop="bigImg(indexs)"
        fit="contain"
      >
        <img :src="items" class="swip_img" />
      </van-swipe-item>
    </van-swipe>

    <div v-show="imgList.length!=0" class="decs">
      <!--商品详情  -->
      <van-row class="goodesDerail">
        <p style="width:100%;color:#fff !important;">商品：{{ShoppingInfo.content}}</p>
        <p style="color:#fff !important;">
          价格:
          <span
            style="font-size:0.6rem;color:#fff !important;"
          >{{formatprice(ShoppingInfo.price)}}</span>
        </p>
        <span style="color:#fff !important;">原来价格:</span>
        <span
          class="van-card__origin-price"
          style="color:#fff !important;"
        >{{formatprice(ShoppingInfo.originalPrice)}}</span>
      </van-row>
      <van-contact-card type="edit" :name="name" :tel="phone" :editable="false" />
    </div>

    <!-- 底部购物车 -->
    <div v-show="imgList.length!=0">
      <van-collapse v-model="activeNames">
        <van-collapse-item title="收货地址" name="1" icon="location-o">
          <van-field
            v-model="address"
            rows="1"
            autosize
            label="地址"
            type="textarea"
            placeholder="请输入收货地址"
          />

          <van-cell value="购物数量">
            <!-- 使用 title 插槽来自定义标题 -->
            <template #right-icon>
              <van-stepper v-model="num" min="1" integer :max="ShoppingInfo.amount" />
            </template>
          </van-cell>
        </van-collapse-item>
      </van-collapse>

      <!-- 底部购物车 -->
      <div>
        <van-action-bar>
          <van-badge :content="myChartList.length" max="99">
            <van-action-bar-icon icon="cart-o" text="购物车" @click="byGoods" />
          </van-badge>

          <van-action-bar-button type="warning" text="加入购物车" @click="addChart" />
          <van-action-bar-button type="danger" text="立即购买" @click="payMeonyOne" />
        </van-action-bar>
      </div>

      <!-- 弹出框 -->

      <van-popup
        :show="show"
        closeable
        position="bottom"
        :close-on-popstate="true"
        @click-close-icon="show=false"
        :style="{ height: '70%' }"
      >
        <!-- 购物车内容 -->

        <div class="content">
          <div v-if="!empty">
            <!-- 购物车内容 -->
            <div v-for="(item,index) in myChartList" :key="index">
              <van-swipe-cell>
                <van-swipe-cell>
                  <van-card
                    style="margin-bottom: 10px;"
                    :num="item.amount"
                    :price="item.goods.price"
                    :desc="item.goods.content"
                    :title="item.goods.title"
                    :thumb="item.goods.imgList[0]"
                    class="goods-card"
                    @click="seeDetail(item.id)"
                  />
                  <template #right>
                    <van-button
                      style="height:100px;"
                      square
                      text="删除"
                      type="danger"
                      class="delete-button"
                      @click="delGoods(item.goods.id)"
                    />
                  </template>

                  <!-- <van-stepper v-model="item.amount" min="1" integer :max="ShoppingInfo.amount" /> -->
                </van-swipe-cell>
              </van-swipe-cell>
            </div>
            <!--计算总价  -->
            <van-submit-bar :price="payMoney" button-text="提交订单" @submit="payAllMonetyByZFB">
              <!-- <van-checkbox v-model="checked">全选</van-checkbox> -->
              <template #tip>收货地址:{{ShoppingInfo.user.address}}</template>
            </van-submit-bar>
          </div>

          <van-empty v-else image="error" description="暂无商品，快去商场看看吧(*￣︶￣)" />
        </div>
      </van-popup>
    </div>
    <!-- 弹出框 -->
  </div>
</template>

<script>
import myheader from '../../../comon/myheader.vue'
import Chart from '../../../comon/chart.vue'
import { Dialog, Notify } from 'vant'
import { ImagePreview } from 'vant'
import { Toast } from 'vant'
export default {
  inject: ['reload'],
  components: {
    myheader,
    Chart,
  },

  data() {
    return {
      userId: 1,
      ShoppingInfo: [],
      name: '', // 商家姓名
      phone: '', // 商家联系方式
      empty: false, // 空图片
      address: '',
      activeNames: ['1'],
      num: 1, // 购买商品的数量
      imgList: [],
      myChartList: [], // 购物车列表
      show: false, // 购物车弹出框
      payMoney: 0, // 购物总金额
      clearChart: [], //清空购物车列表
    }
  },
  created() {
    this.init()
    // this.initChart()
  },

  methods: {
    formatprice(val) {
      return '￥' + val
    },
    async init() {
      const res = await this.$axios.get(
        '/goods/group/info/' + this.$route.params.id
      )
      if (res.data.code == 200) {
        this.ShoppingInfo = res.data.data
        this.name = res.data.data.user.username
        this.phone = res.data.data.user.phone
        this.title = this.ShoppingInfo.title
        this.address = this.ShoppingInfo.user.address
        this.imgList = this.ShoppingInfo.imgList
      }
    },

    // 支付宝沙箱支付
    //支付账号:nwnppd2252@sandbox.com
    // 支付密码 :111111
    payMeonyOne() {
      if (!this.$store.getters.getUserInfo) {
        Toast('请先登录才能购买呦 (づ￣3￣)づ╭❤～')
        this.$router.push('/login')
      } else if (this.address == '') {
        Notify({ type: 'warning', message: '亲~您还没有填写收货地址哟！' })
      } else {
        this.userId = this.$store.getters.getUserInfo.id
        Dialog.confirm({
          title: '购物提示',
          message:
            '确认购买' +
            this.ShoppingInfo.title +
            '数量' +
            this.num +
            '需要支付' +
            this.ShoppingInfo.price * this.num +
            '元',
        })
          .then(() => {
            // on confirm
            //  [this.ShoppingInfo.id]:1
            this.$axios
              .post(
                '/order/alipayGroup',

                JSON.stringify({
                  goodsMap: { [this.ShoppingInfo.id]: this.num.toString() },
                  address: this.address,
                  userId: this.$store.getters.getUserInfo.id.toString(),
                })
              )
              .then((resp) => {
                // 添加之前先删除一下，如果单页面，页面不刷新，添加进去的内容会一直保留在页面中，二次调用form表单会出错
                const divForm = document.getElementsByTagName('div')
                if (divForm.length) {
                  document.body.removeChild(divForm[0])
                }
                const div = document.createElement('div')
                div.innerHTML = resp.data // data就是接口返回的form 表单字符串
                document.body.appendChild(div)
                document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
                document.forms[0].submit()
              })
          })
          .catch(() => {
            // on cancel
          })
      }
    },

    // 大图
    bigImg(indexs) {
      ImagePreview({
        images: this.imgList, // 预览图片的那个数组
        loop: false,
        closeable: true,
        startPosition: indexs, // 指明预览第几张图
      })
    },
    //初始化购物车
    async initChart() {
      if (!this.$store.getters.getUserInfo) {
        Toast('请先登录呦 (づ￣3￣)づ╭❤～')
        this.$router.push('/login')
      } else {
        const res = await this.$axios.get(
          '/store/cart/group/show/' + this.userId
        )
        if (res.data.code == 200) {
          this.myChartList = res.data.data

          if (this.myChartList.length != 0) {
            this.empty = false
          } else {
            this.empty = true
          }
          this.payAllMonety()
        }
      }
    },
    // 添加商品进购物车
    async addChart() {
      if (!this.$store.getters.getUserInfo) {
        Toast('请先登录呦 (づ￣3￣)づ╭❤～')
        this.$router.push('/login')
      }
      {
        await this.initChart()

        let count = 0
        for (let i = 0; i < this.myChartList.length; i++) {
          if (
            parseInt(this.myChartList[i].goods.id) ==
            parseInt(this.$route.params.id)
          ) {
            count += this.myChartList[i].amount
            break
          }
        }

        const res = await this.$axios.post('/store/cart/group/modify', {
          userId: this.userId,
          goodsId: this.$route.params.id,
          amount: this.num + count,
        })

        if (res.data.code == 200) {
          Toast.success('加入购物车成功')
          this.initChart()
        }
      }
    },
    // 删除商品
    async delGoods(goodsId) {
      const res = await this.$axios.post('/store/cart/group/modify', {
        userId: this.userId,
        goodsId: goodsId,
        amount: 0,
      })
      if (res.data.code == 200) {
        Toast.success('删除成功')
        this.initChart()
      }
    },
    //弹出购物车
    byGoods() {
      this.show = !this.show
      this.initChart()
    },

    // 付钱  单价 * 金额
    payAllMonetyByZFB() {
      // 支付宝付钱

      if (!this.$store.getters.getUserInfo) {
        Toast('请先登录才能购买呦 (づ￣3￣)づ╭❤～')

        this.$router.push('/login')
      } else if (this.myChartList.length == 0) {
        Notify({ type: 'warning', message: '亲~您还没有选中任何商品哟！' })
      } else if (this.address == '') {
        Notify({ type: 'warning', message: '亲~您还没有填写收货地址哟！' })
      } else {
        const that = this
        Dialog.confirm({
          title: '购物提示',
          message:
            '确认购买' +
            that.myChartList.length +
            '件商品' +
            '需要支付' +
            that.payMoney +
            '元',
        })
          .then(() => {
            let goodsMap = new Map()
            that.clearChart = []
            for (var i = 0; i < that.myChartList.length; i++) {
              goodsMap.set(
                that.myChartList[i].goods.id.toString(),
                that.myChartList[i].amount.toString()
              )

              that.clearChart.push(that.myChartList[i].goods.id)
            }
            let obj = Object.create(null)
            for (let [k, v] of goodsMap) {
              obj[k] = v
            }
            goodsMap = JSON.stringify(obj).replace(/[\\]/g, '')

            console.log(goodsMap)

            that.$axios
              .post(
                '/order/alipayGroup',
                JSON.stringify({
                  address: that.address,
                  userId: that.$store.getters.getUserInfo.id.toString(),
                  goodsMap: JSON.parse(goodsMap),
                })
              )
              .then((resp) => {
                that.clearCharts()
                // 添加之前先删除一下，如果单页面，页面不刷新，添加进去的内容会一直保留在页面中，二次调用form表单会出错
                const divForm = document.getElementsByTagName('div')
                if (divForm.length) {
                  document.body.removeChild(divForm[0])
                }
                const div = document.createElement('div')
                div.innerHTML = resp.data // data就是接口返回的form 表单字符串
                document.body.appendChild(div)
                document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
                document.forms[0].submit()
              })
          })
          .catch(() => {
            // on cancel
          })
      }
    },
    // 结算金额
    payAllMonety() {
      let total = 0
      if (this.myChartList.length != 0) {
        this.myChartList.forEach((e) => {
          total += e.amount * e.goods.price
        })
        this.payMoney = total * 100
      } else {
        this.payMoney = 0
      }
    },
    // 查看购物车的商品跳转
    seeDetail(id) {
      this.$router.push('/ShoppingInfo/' + id)
      this.reload
    },
    //支付完成清空购物车
    async clearCharts() {
      let flag = false
      for (let index = 0; index < this.clearChart.length; index++) {
        const res = await this.$axios.post('/store/cart/group/modify', {
          userId: this.userId,
          goodsId: this.clearChart[index],
          amount: 0,
        })

        if (res.data.code == 200) {
          flag = true
        } else {
          flag = false
          break
        }
      }
      if (flag) {
        Toast.success('删除成功')
        this.initChart()
      }
    },

    submitRecruit() {
      if (!this.$store.getters.getUserInfo) {
        Toast('请先登录呦 (づ￣3￣)づ╭❤～')
        this.$router.push('/login')
      } else {
        this.$router.push(
          '/ShoppingDetail/' + this.$store.getters.getUserInfo.id
        )
      }
    },
  },
}
</script>

<style scoped>
.ShoppingInfo {
  margin-top: 46px;
  margin-bottom: 80px;
}

.van-cell {
  font-size: 17px !important;
}
.goodesDerail p {
  font-size: 0.4rem;
  text-indent: 2em;
  padding: 5px;
}
.goodesDerail span {
  font-size: 0.4rem;
  padding: 14px 3px;
}
.van-card__origin-price {
  font-size: 1em !important;
  color: #fff;
}

.yield .decs {
  color: #fff !important;
  background: #fd5632;
}
.edit-address {
  color: #1989fa;
}

.content {
  padding: 50px 0 !important;
}
</style>
